import argparse
import sys
import os

parser = argparse.ArgumentParser(description='Train data for cross validation')
parser.add_argument('--kfold', required=True, type=int)
parser.add_argument('--perm', nargs='*', required=True, type=int)
parser.add_argument('--videos', nargs='*', required=True)
args = parser.parse_args()

if len(args.perm) != len(args.videos):
	print("You must provide a permutation of the numbers 1 to n, where n is the number of videos")
	sys.exit(1)

if len(args.videos) % args.kfold != 0 or len(args.videos) <= args.kfold:
	print("k-fold cross validation requires video count less than and to be divisible by k")
	sys.exit(2)
	
if args.kfold < 2:
	print("k-fold cross validation requires k > 1")
	sys.exit(3)

def vidperm( vids, perm ):
	return [ vids[x] for x in perm]

def doCrossTrain( vids, perm, kfold ):
	setsize = len(vids)//kfold
	for i in range(kfold):
		videoList = vidperm(args.videos, args.perm)
		testingList = videoList[i*setsize:(i+1)*setsize]
		trainingList = videoList[0:i*setsize]
		trainingList.extend(videoList[(i+1)*setsize:])
		
		#HACK!!
		try:
			testingList.remove("loS1Ellen1v3")
		except ValueError: #loS1Ellen1v3 not in list
			pass
		try:
			trainingList.remove("loS1Ellen1v3")
		except ValueError: #loS1Ellen1v3 not in list
			pass
		
		testingVideos = "@".join(testingList) #autotest syntax
		trainingVideos = " ".join(trainingList) #MLTrainer syntax
		
		os.system("echo testing=\""+testingVideos+"\n\" "
			+"1>>svmdata/C"+str(i)+"_train.log")
		os.system("echo training=\""+trainingVideos+"\n\" "
			+"1>>svmdata/C"+str(i)+"_train.log")
			
		os.system(
				"./MLTrainer.out  C"+str(i)+" C"+str(i)+" "
				+  trainingVideos
				+" 1>>svmdata/C"+str(i)+"_train.log")

		print("Completed C"+str(i)+"\n")

doCrossTrain( args.videos, args.perm, args.kfold)



"""

		if (i+1) % 3 == 0:
			#os.system(
			print(
				"./MLTrainer.out  C"+str(i)+" C"+str(i)+" "
				+" ".join( vidperm(args.videos, args.perm, i)[setsize:] )
				+" 1>>svmdata/C"+str(i)+"_train.log")
		else:
			#os.system(
			print(
				"./MLTrainer.out C"+str(i)+" C"+str(i)+" "
				+" ".join( vidperm(args.videos, args.perm, i)[setsize:] )
				+" 1>>svmdata/C"+str(i)+"_train.log &")


"""